<!DOCTYPE html>
<html>
<head>
    <title>{{.Title}}</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        * { box-sizing: border-box; }
        body { 
            font-family: 'Microsoft YaHei', Arial, sans-serif; 
            margin: 0; 
            padding: 20px; 
            background: #f8f9fa; 
        }
        .container { 
            max-width: 1400px; 
            margin: 0 auto; 
        }
        .header { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 20px;
        }
        .card { 
            background: white; 
            border-radius: 10px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.1); 
            margin-bottom: 20px; 
            overflow: hidden;
        }
        .card-header {
            background: #f8f9fa;
            padding: 20px;
            border-bottom: 1px solid #eee;
        }
        .card-body { 
            padding: 20px; 
        }
        table { 
            width: 100%; 
            border-collapse: collapse; 
            background: white; 
        }
        th, td { 
            border: 1px solid #dee2e6; 
            padding: 12px; 
            text-align: left; 
        }
        th { 
            background-color: #f8f9fa; 
            font-weight: 600; 
            color: #495057;
        }
        .btn { 
            padding: 8px 16px; 
            margin: 2px; 
            text-decoration: none; 
            border: none; 
            border-radius: 5px; 
            cursor: pointer; 
            font-size: 14px; 
            transition: all 0.3s; 
            display: inline-block;
        }
        .btn:hover { 
            opacity: 0.9; 
            transform: translateY(-1px); 
        }
        .btn-primary { 
            background: #007bff; 
            color: white; 
        }
        .btn-success { 
            background: #28a745; 
            color: white; 
        }
        .btn-danger { 
            background: #dc3545; 
            color: white; 
        }
        .btn-warning { 
            background: #ffc107; 
            color: #212529; 
        }
        .btn-info {
            background: #17a2b8;
            color: white;
        }
        .btn-sm { 
            padding: 6px 12px; 
            font-size: 12px; 
        }
        .form-group { 
            margin-bottom: 15px; 
        }
        .form-row { 
            display: flex; 
            flex-wrap: wrap; 
            margin: 0 -10px; 
        }
        .form-col { 
            flex: 1; 
            padding: 0 10px; 
            min-width: 200px; 
        }
        label { 
            display: block; 
            margin-bottom: 5px; 
            font-weight: 500; 
            color: #495057;
        }
        input, select { 
            width: 100%; 
            padding: 10px; 
            border: 2px solid #e9ecef; 
            border-radius: 5px; 
            font-size: 14px; 
            transition: border-color 0.3s;
        }
        input:focus, select:focus { 
            border-color: #007bff; 
            outline: none; 
            box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
        }
        .search-box { 
            display: flex; 
            gap: 10px; 
            margin-bottom: 20px; 
        }
        .search-box input { 
            flex: 1; 
        }
        .pagination { 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            margin: 20px 0; 
            gap: 10px; 
        }
        .status-in { 
            color: #28a745; 
            font-weight: 500; 
        }
        .status-out { 
            color: #dc3545; 
            font-weight: 500; 
        }
        .actions { 
            display: flex; 
            flex-wrap: wrap; 
            gap: 5px;
        }
        .modal { 
            display: none; 
            position: fixed; 
            z-index: 1000; 
            left: 0; 
            top: 0; 
            width: 100%; 
            height: 100%; 
            background: rgba(0,0,0,0.5); 
        }
        .modal-content { 
            background: white; 
            margin: 5% auto; 
            padding: 30px; 
            border-radius: 10px; 
            width: 90%; 
            max-width: 500px; 
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }
        .modal-header { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            margin-bottom: 20px; 
            border-bottom: 1px solid #eee;
            padding-bottom: 15px;
        }
        .close { 
            font-size: 28px; 
            cursor: pointer; 
            color: #6c757d;
        }
        .close:hover {
            color: #495057;
        }
        .alert { 
            padding: 12px 15px; 
            border-radius: 5px; 
            margin-bottom: 15px; 
            border-left: 4px solid;
        }
        .alert-success { 
            background: #d4edda; 
            color: #155724; 
            border-color: #c3e6cb; 
        }
        .alert-error { 
            background: #f8d7da; 
            color: #721c24; 
            border-color: #f5c6cb; 
        }
        .code-status {
            font-size: 12px;
            margin-top: 5px;
        }
        .valid { color: #28a745; }
        .invalid { color: #dc3545; }
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        .btn-secondary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>{{.Title}}</h1>
            <div>
                <button class="btn btn-primary" onclick="showAddModal()">添加商品</button>
                <a href="/products/export" class="btn btn-success">导出Excel</a>
                <a href="/logout" class="btn btn-danger">退出登录</a>
            </div>
        </div>

        <!-- 搜索框 -->
        <div class="card">
            <div class="card-body">
                <form id="searchForm" onsubmit="return false;">
                    <div class="form-row">
                        <div class="form-col">
                            <input type="text" name="search" value="{{.Search}}" placeholder="搜索商品名称或唯一码...">
                        </div>
                        <div class="form-col">
                            <button type="button" class="btn btn-primary" onclick="searchProducts()" style="width: auto;">搜索</button>
                            <button type="button" class="btn btn-warning" onclick="resetSearch()" style="width: auto;">重置</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- 商品列表 -->
        <div class="card">
            <div class="card-body">
                <div style="overflow-x: auto;">
                    <table>
                        <thead>
                            <tr>
                                <th>唯一码</th>
                                <th>商品名称</th>
                                <th>价格</th>
                                <th>入库时间</th>
                                <th>出库时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {{range .Products}}
                            <tr>
                                <td><strong>{{.UniqueCode}}</strong></td>
                                <td>{{.Name}}</td>
                                <td>¥{{printf "%.2f" .Price}}</td>
                                <td>{{.StorageTime.Format "2006-01-02 15:04:05"}}</td>
                                <td>
                                    {{if not .OutboundTime.IsZero}}
                                        {{.OutboundTime.Format "2006-01-02 15:04:05"}}
                                    {{else}}
                                        -
                                    {{end}}
                                </td>
                                <td>
                                    {{if eq .Status "sold"}}
                                        <span class="status-out">已出售</span>
                                    {{else}}
                                        <span class="status-in">在库</span>
                                    {{end}}
                                </td>
                                <td>
                                    <div class="actions">
                                        {{if eq .Status "in_storage"}}
                                            <button class="btn btn-success btn-sm" onclick="sellProduct('{{.UniqueCode}}')">出售</button>
                                            <button class="btn btn-primary btn-sm" onclick="editProduct('{{.UniqueCode}}')">编辑</button>
                                        {{end}}
                                        <button class="btn btn-danger btn-sm" onclick="deleteProduct('{{.UniqueCode}}')">删除</button>
                                    </div>
                                </td>
                            </tr>
                            {{else}}
                            <tr>
                                <td colspan="7" style="text-align: center; padding: 40px; color: #6c757d;">
                                    暂无商品数据
                                </td>
                            </tr>
                            {{end}}
                        </tbody>
                    </table>
                </div>

                <!-- 分页 - 完全使用JavaScript处理 -->
                {{if gt .Total 0}}
                <div class="pagination">
                    <button class="btn btn-sm btn-primary" id="prevBtn">上一页</button>
                    
                    <span style="margin: 0 15px;" id="pageInfo">
                        第 {{.Page}} 页 - 共 {{.Total}} 条记录
                    </span>
                    
                    <button class="btn btn-sm btn-primary" id="nextBtn">下一页</button>
                </div>
                {{end}}
            </div>
        </div>
    </div>

    <!-- 添加/编辑商品模态框 -->
    <div id="productModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">添加商品</h3>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>
            <form id="productForm">
                <input type="hidden" id="editMode" value="add">
                
                <div class="form-group">
                    <label for="unique_code">唯一码 (16位字母数字):</label>
                    <input type="text" id="unique_code" name="unique_code" maxlength="16" 
                           pattern="[a-zA-Z0-9]{16}" title="请输入16位字母数字组合"
                           oninput="checkUniqueCode()" required>
                    <div id="codeStatus" class="code-status"></div>
                </div>
                
                <div class="form-group">
                    <label for="name">商品名称:</label>
                    <input type="text" id="name" name="name" required>
                </div>
                
                <div class="form-group">
                    <label for="price">价格:</label>
                    <input type="number" id="price" name="price" step="0.01" min="0" required>
                </div>
                
                <div style="text-align: right; margin-top: 30px;">
                    <button type="button" class="btn btn-warning" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary" id="submitBtn">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 分页相关变量
        const currentPage = {{.Page}};
        const totalRecords = {{.Total}};
        const pageSize = {{.PageSize}};

        document.addEventListener('DOMContentLoaded', function() {
            // 设置分页按钮状态
            setupPagination();
        });

        function setupPagination() {
            const prevBtn = document.getElementById('prevBtn');
            const nextBtn = document.getElementById('nextBtn');
            const pageInfo = document.getElementById('pageInfo');
            
            if (prevBtn && nextBtn && pageInfo) {
                // 计算总页数
                const totalPages = Math.ceil(totalRecords / pageSize);
                
                // 更新页面信息
                pageInfo.textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页 (${totalRecords} 条记录)`;
                
                // 设置上一页按钮状态
                if (currentPage <= 1) {
                    prevBtn.disabled = true;
                    prevBtn.classList.remove('btn-primary');
                    prevBtn.classList.add('btn-secondary');
                } else {
                    prevBtn.disabled = false;
                    prevBtn.classList.remove('btn-secondary');
                    prevBtn.classList.add('btn-primary');
                    prevBtn.onclick = function() { changePage(currentPage - 1); };
                }
                
                // 设置下一页按钮状态
                if (currentPage >= totalPages) {
                    nextBtn.disabled = true;
                    nextBtn.classList.remove('btn-primary');
                    nextBtn.classList.add('btn-secondary');
                } else {
                    nextBtn.disabled = false;
                    nextBtn.classList.remove('btn-secondary');
                    nextBtn.classList.add('btn-primary');
                    nextBtn.onclick = function() { changePage(currentPage + 1); };
                }
            }
        }

        function showAddModal() {
            document.getElementById('modalTitle').textContent = '添加商品';
            document.getElementById('editMode').value = 'add';
            document.getElementById('productForm').reset();
            document.getElementById('unique_code').readOnly = false;
            document.getElementById('codeStatus').innerHTML = '';
            document.getElementById('productModal').style.display = 'block';
        }

        function editProduct(code) {
            // 获取商品详情
            fetch('/products/detail?code=' + code)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const product = data.data;
                        document.getElementById('modalTitle').textContent = '编辑商品';
                        document.getElementById('editMode').value = 'edit';
                        document.getElementById('unique_code').value = product.unique_code;
                        document.getElementById('unique_code').readOnly = true;
                        document.getElementById('name').value = product.name;
                        document.getElementById('price').value = product.price;
                        document.getElementById('codeStatus').innerHTML = '';
                        document.getElementById('productModal').style.display = 'block';
                    } else {
                        alert('获取商品详情失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取商品详情失败');
                });
        }

        function closeModal() {
            document.getElementById('productModal').style.display = 'none';
        }

        function checkUniqueCode() {
            const code = document.getElementById('unique_code').value;
            const codeStatus = document.getElementById('codeStatus');
            const editMode = document.getElementById('editMode').value;
            
            if (code.length === 0) {
                codeStatus.innerHTML = '';
                return;
            }
            
            if (!/^[a-zA-Z0-9]{16}$/.test(code)) {
                codeStatus.innerHTML = '<span class="invalid">格式错误：必须是16位字母数字组合</span>';
                return;
            }
            
            // 编辑模式下不检查唯一码是否重复
            if (editMode === 'add') {
                fetch('/products/check-code?code=' + code)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            codeStatus.innerHTML = '<span class="valid">✓ 唯一码可用</span>';
                        } else {
                            codeStatus.innerHTML = '<span class="invalid">✗ ' + data.message + '</span>';
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        codeStatus.innerHTML = '<span class="invalid">检查失败</span>';
                    });
            }
        }

        document.getElementById('productForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const code = document.getElementById('unique_code').value;
            if (!/^[a-zA-Z0-9]{16}$/.test(code)) {
                alert('唯一码必须是16位字母数字组合');
                return;
            }
            
            const formData = new FormData(this);
            const mode = document.getElementById('editMode').value;
            const url = mode === 'add' ? '/products/add' : '/products/update';
            
            fetch(url, {
                method: 'POST',
                body: formData
            }).then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    closeModal();
                    location.reload();
                } else {
                    alert('错误: ' + data.message);
                }
            });
        });

        function sellProduct(code) {
            if (confirm('确定要出售这个商品吗？')) {
                const formData = new FormData();
                formData.append('code', code);
                
                fetch('/products/sell', {
                    method: 'POST',
                    body: formData
                }).then(response => response.json())
                .then(data => {
                    alert(data.message);
                    location.reload();
                });
            }
        }

        function deleteProduct(code) {
            if (confirm('确定要删除这个商品吗？此操作不可恢复！')) {
                const formData = new FormData();
                formData.append('code', code);
                
                fetch('/products/delete', {
                    method: 'POST',
                    body: formData
                }).then(response => response.json())
                .then(data => {
                    alert(data.message);
                    location.reload();
                });
            }
        }

        function searchProducts() {
            const form = document.getElementById('searchForm');
            const formData = new FormData(form);
            const params = new URLSearchParams(formData);
            window.location.href = '/products?' + params.toString();
        }

        function resetSearch() {
            window.location.href = '/products';
        }

        function changePage(page) {
            const url = new URL(window.location);
            url.searchParams.set('page', page);
            window.location.href = url.toString();
        }

        // 关闭模态框
        window.onclick = function(event) {
            const modal = document.getElementById('productModal');
            if (event.target === modal) {
                closeModal();
            }
        }
    </script>
</body>
</html>